<template>
  <view class="common-car">
    <view class="empty-shop-car" v-if="isEmpty">
      <image
        src="../../../static/images/empty_shop_car.png"
        class="empty-shop-car-image"
        mode="aspectFit"
      ></image>
      <text class="empty-tip">当前您的购物车是空的</text>
      <view class="empty-shop-car-btn" @click="goShopping">
        <text>去逛逛</text>
      </view>
    </view>
    <view class="shop-car" v-else>
      <view class="cart-header">
        <view class="header-left">
          <text class="cart-title">购物车</text>
        </view>
        <view class="header-right">
          <button class="edit-btn" @tap="cut" plain>
            {{ isCut ? '编辑' : '完成' }}
          </button>
        </view>
      </view>
      
      <view class="goods-list">
        <view 
          class="goods-item" 
          v-for="(goods, goodsIndex) in formattedCartList[0].goods" 
          :key="goods.id"
        >
          <view class="goods-checkbox" :class="{'edit-mode': !isCut}" @tap="() => goodsCheck(0, goodsIndex, goods.checked)">
            <image
              :src="goods.checked === 1 ? '../../../static/images/select.png' : '../../../static/images/not_select.png'"
              class="checked-image"
              :class="{'normal-mode': isCut}"
              mode="aspectFit"
            ></image>
          </view>
          
          <view class="goods-content">
            <image :src="goods.img" class="goods-image" mode="aspectFill"></image>
            <view class="goods-info">
              <view class="title-row">
                <text class="goods-title">{{ goods.title }}</text>
                <text class="goods-spec">规格：{{ goods.remark }}</text>
              </view>
              <view class="price-row">
                <text class="current-price">¥{{ goods.discountPrice || goods.price }}</text>
                <text class="original-price" v-if="goods.discountPrice">¥{{ goods.price }}</text>
              </view>
              <view class="subtotal-row">
                <text class="subtotal">小计：¥{{ goods.subtotal }}</text>
              </view>
              <view class="quantity-control">
                <view v-if="!isCut" class="quantity-btn minus" @tap.stop="() => sub(0, goodsIndex)">
                  <uni-icons type="minus" size="18" color="#333"></uni-icons>
                </view>
                <view v-if="!isCut" class="quantity-input">
                  <text>{{ goods.number }}</text>
                </view>
                <view v-if="!isCut" class="quantity-btn plus" @tap.stop="() => add(0, goodsIndex)">
                  <uni-icons type="plus" size="18" color="#333"></uni-icons>
                </view>
                <view v-else class="quantity-text">
                  <text class="number-text">{{ goods.number }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <view class="statistics-box" :class="{ 'iPhoneX': iPhoneX }">
        <view class="statistics">
          <view class="statistics-left" @tap="allCheck">
            <view class="all-select-checkbox" :class="{'edit-mode': !isCut}">
              <image
                :src="isAllSelected ? '../../../static/images/select.png' : '../../../static/images/not_select.png'"
                class="checked-image"
                :class="{'normal-mode': isCut}"
                mode="aspectFit"
              ></image>
            </view>
            <text>全选</text>
          </view>
          <view class="statistics-right" v-if="isCut">
            <view class="total-price">
              <text>总计：</text>
              <text class="price-number">¥{{ totalAmount }}</text>
            </view>
            <view class="checkout-btn" @tap="accounts">
              <text>结算</text>
            </view>
          </view>
          <view class="statistics-right" v-else>
            <view class="delete-btn" @tap="delect">
              <text>删除</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useCartStore } from '../../../store/cartStore'
import { storeToRefs } from 'pinia'

const cartStore = useCartStore()
const { cartList, totalAmount, isAllSelected } = storeToRefs(cartStore)

const props = defineProps({
  list: {
    type: [Object, Array],
    default: () => ({}),
  },
})
const emit = defineEmits(['delect', 'accounts'])

const isEmpty = computed(() => !cartList.value || cartList.value.length === 0)
const iPhoneX = ref(false)
const isCut = ref(true)

const formattedCartList = computed(() => {
  if (!cartList.value) return []
  
  const defaultStore = {
    name: '水果店',
    checked: 1,
    goods: cartList.value.map(item => ({
      id: item.id,
      img: item.fruitImage || '',
      title: item.fruitName,
      remark: item.specifications || '',
      price: Number(item.price).toFixed(2),
      discountPrice: item.discountPrice ? Number(item.discountPrice).toFixed(2) : null,
      number: item.quantity,
      checked: item.selected,
      subtotal: Number(item.subtotal).toFixed(2)
    }))
  }
  
  defaultStore.checked = defaultStore.goods.every(item => item.checked === 1) ? 1 : 2
  
  return [defaultStore]
})

onMounted(async () => {
  iPhoneX.value = uni.getStorageSync('iPhoneX')
  await loadCartData()
})

const loadCartData = async () => {
  try {
    await cartStore.loadCartList()
    await cartStore.updateCartInfo()
  } catch (error) {
    uni.showToast({
      title: '加载购物车数据失败',
      icon: 'none'
    })
  }
}

const goodsCheck = async (storeIndex, goodsIndex, goodsChecked) => {
  try {
    const item = formattedCartList.value[storeIndex].goods[goodsIndex]
    const newSelected = goodsChecked === 1 ? 0 : 1;
    await cartStore.updateItemSelected(item.id, newSelected)
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

const storeCheck = async (storeIndex, storeCheckValue) => {
  try {
    const store = formattedCartList.value[storeIndex]
    const newSelected = storeCheckValue === 1 ? 0 : 1;
    await Promise.all(
      store.goods.map(item => cartStore.updateItemSelected(item.id, newSelected))
    )
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

const sub = async (storeIndex, goodsIndex) => {
  try {
    const item = formattedCartList.value[storeIndex].goods[goodsIndex]
    if (item.number <= 1) {
      uni.showModal({
        title: '提示',
        content: '确定要删除该商品吗？',
        success: async (res) => {
          if (res.confirm) {
            await cartStore.deleteCartItem(item.id)
          }
        }
      })
    } else {
      const cartDTO = {
        quantity: item.number - 1,
        selected: item.checked
      }
      await cartStore.updateCartItem(item.id, cartDTO)
    }
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

const add = async (storeIndex, goodsIndex) => {
  try {
    const item = formattedCartList.value[storeIndex].goods[goodsIndex]
    const cartDTO = {
      quantity: item.number + 1,
      selected: item.checked
    }
    await cartStore.updateCartItem(item.id, cartDTO)
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

const allCheck = async () => {
  try {
    const newSelected = isAllSelected.value ? 0 : 1;
    await cartStore.toggleSelectAll(newSelected)
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

const accounts = () => {
  const selectedItems = formattedCartList.value
    .flatMap(store => store.goods)
    .filter(item => item.checked === 1)

  if (selectedItems.length === 0) {
    uni.showToast({
      title: '请选择要结算的商品',
      icon: 'none'
    })
    return
  }

  emit('accounts', selectedItems)
}

const delect = async () => {
  const selectedItems = formattedCartList.value
    .flatMap(store => store.goods)
    .filter(item => item.checked === 1)

  if (selectedItems.length === 0) {
    uni.showToast({
      title: '请选择要删除的商品',
      icon: 'none'
    })
    return
  }

  uni.showModal({
    title: '提示',
    content: '确定要删除选中的商品吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await Promise.all(
            selectedItems.map(item => cartStore.deleteCartItem(item.id))
          )
          emit('delect', selectedItems)
        } catch (error) {
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

const cut = () => {
  isCut.value = !isCut.value
  
  if (!isCut.value) {
    cartStore.toggleSelectAll(0);
  }
  
  if (isCut.value) {
    loadCartData()
  }
}

const goShopping = () => {
  uni.switchTab({
    url: '/pages/home/index'
  })
}
</script>

<style lang="scss" scoped>
.common-car {
  width: 750rpx;
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
  position: relative;
}

.shop-car {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.cart-header {
  width: 100%;
  height: 88rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10rpx;
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
  box-sizing: border-box;
  
  .header-left {
    flex: 1;
    display: flex;
    align-items: center;
    padding-left: 20rpx;
  }
  
  .header-right {
    width: 120rpx;
    display: flex;
    justify-content: center;
  }
  
  .cart-title {
    font-size: 34rpx;
    font-weight: 500;
    color: #333333;
  }
  
  .edit-btn {
    position: relative;
    z-index: 101;
    min-width: 80rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 28rpx;
    color: #1890ff !important;
    margin: 0;
    padding: 0 15rpx;
    border: none !important;
    background-color: transparent !important;
    line-height: 1;
    
    &::after {
      border: none;
    }
    
    &:active {
      opacity: 0.8;
    }
  }
}

.goods-list {
  padding: 20rpx;
  margin-top: 10rpx;
}

.goods-item {
  background-color: #ffffff;
  border-radius: 12rpx;
  margin-bottom: 20rpx;
  padding: 20rpx;
  display: flex;
  align-items: flex-start;
}

.goods-checkbox {
  padding: 15rpx;
  margin-right: 10rpx;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
  
  &.edit-mode {
    transform: scale(1.05);
  }
  
  .checked-image {
    width: 40rpx;
    height: 40rpx;
    transition: all 0.2s ease;
    border-radius: 50%;
    
    &.normal-mode {
      width: 40rpx;
      height: 40rpx;
      opacity: 0.9;
    }
  }
}

.goods-content {
  flex: 1;
  display: flex;
  
  .goods-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 8rpx;
    background-color: #f5f5f5;
  }
  
  .goods-info {
    flex: 1;
    margin-left: 20rpx;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    position: relative;
    
    .title-row {
      .goods-title {
        font-size: 28rpx;
        color: #333333;
        margin-bottom: 10rpx;
      }
      
      .goods-spec {
        font-size: 24rpx;
        color: #999999;
        display: block;
        margin-bottom: 10rpx;
      }
    }
    
    .price-row {
      display: flex;
      align-items: center;
      margin: 8rpx 0;
      
      .current-price {
        font-size: 32rpx;
        font-weight: 600;
        color: #ff8800;
        margin-right: 10rpx;
      }
      
      .original-price {
        font-size: 24rpx;
        color: #999999;
        text-decoration: line-through;
      }
    }
    
    .subtotal-row {
      margin: 5rpx 0;
      
      .subtotal {
        font-size: 24rpx;
        color: #666666;
      }
    }
    
    .quantity-control {
      display: flex;
      align-items: center;
      position: absolute;
      right: 0;
      bottom: 0;
      
      .quantity-btn {
        width: 50rpx;
        height: 50rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f5f5f5;
        
        &.minus {
          border-radius: 25rpx 0 0 25rpx;
          border: 1rpx solid #ddd;
        }
        
        &.plus {
          border-radius: 0 25rpx 25rpx 0;
          border: 1rpx solid #ddd;
        }
        
        &:active {
          background-color: #e0e0e0;
        }
      }
      
      .quantity-input {
        width: 70rpx;
        height: 50rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f5f5f5;
        border-top: 1rpx solid #ddd;
        border-bottom: 1rpx solid #ddd;
        
        text {
          font-size: 28rpx;
          color: #333;
        }
      }
      
      .quantity-text {
        font-size: 26rpx;
        color: #666;
        padding-right: 10rpx;
        
        .number-text {
          display: inline-block;
          min-width: 36rpx;
          text-align: center;
        }
      }
    }
  }
}

.statistics-box {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #ffffff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
  
  &.iPhoneX {
    padding-bottom: env(safe-area-inset-bottom);
  }
  
  .statistics {
    height: 100rpx;
    padding: 0 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .statistics-left {
      display: flex;
      align-items: center;
      
      .all-select-checkbox {
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
        padding: 5rpx;
        
        &.edit-mode {
          transform: scale(1.05);
        }
      }
      
      .checked-image {
        width: 40rpx;
        height: 40rpx;
        transition: all 0.2s ease;
        border-radius: 50%;
        
        &.normal-mode {
          width: 40rpx;
          height: 40rpx;
          opacity: 0.9;
        }
      }
      
      text {
        font-size: 28rpx;
        color: #333;
        margin-left: 10rpx;
      }
    }
    
    .statistics-right {
      display: flex;
      align-items: center;
      
      .total-price {
        margin-right: 20rpx;
        font-size: 28rpx;
        color: #333333;
        
        .price-number {
          color: #ff8800;
          font-weight: 600;
        }
      }
      
      .checkout-btn {
        width: 200rpx;
        height: 70rpx;
        background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
        border-radius: 35rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        
        text {
          color: #ffffff;
          font-size: 28rpx;
          font-weight: 500;
        }
        
        &:active {
          opacity: 0.9;
        }
      }
      
      .delete-btn {
        width: 160rpx;
        height: 70rpx;
        background-color: #ff4d4f;
        border-radius: 35rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        
        text {
          color: #ffffff;
          font-size: 28rpx;
          font-weight: 500;
        }
        
        &:active {
          opacity: 0.9;
        }
      }
    }
  }
}

.empty-shop-car {
  width: 100%;
  min-height: 80vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40rpx;
  
  .empty-shop-car-image {
    width: 340rpx;
    height: 278rpx;
    margin-bottom: 40rpx;
  }
  
  .empty-tip {
    font-size: 32rpx;
    color: #666;
    margin-bottom: 50rpx;
  }
  
  .empty-shop-car-btn {
    width: 240rpx;
    height: 90rpx;
    background: #ff8800;
    border-radius: 45rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    text {
      font-size: 32rpx;
      color: #ffffff;
    }
  }
}
</style>
